
var bodyBgColor;

$(document).ready(function(){

	$.ajaxSetup ({ cache: false });

	// add intial data to the DOM
	init_data();
	
	// Hide all the edit elements
	$(".edit").hide();	

	// All the display elements should show linebreaks(<br>) on /n
	$(".display").each(	function() { display_with_linebreaks($(this)); });
	// Hover on display elements should change the element background color
	bodyBgColor = $("BODY").css("background-color");
	$(".display").hover(
					function(){ $(this).css({"background-color":"#ADFF2F", "cursor":"default"})},
					function(){ $(this).css({"background-color":"#dedeff", "cursor":"auto"})}
	);
	// click on the display element should activate the editing
	$(".display").bind("click", function(e){ activate_edit(e);});				
	
	// Hide all the input boxes of add class
	$(".addInputBoxes").hide();
	// Click on addMore buttons should start add functionality
	$(".plusButton").bind("click", function(e){ add_more(e);});	
	
	// Delete button
	$(".delete_button").hover(
					function(){ $(this).css({"background-color":"#FF0000", "cursor":"default"})},
					function(){ $(this).css({"background-color":"#dedeff", "cursor":"auto"})}
	);
	$(".delete_button").bind("click", function(e){ delete_it2(e); });	
	
});

function delete_it2(e)
{
	var partName = $(e.target).parents(".part").eq(0).attr("id");
	delete_it(e,'',partName);		// function is defined in resume_common.js, expects (event,[title],[partName])
}

function activate_edit(e)
{
	// hide the display element
	$(e.target).hide();
	
	// show the corresponding edit element
	var editElement = $(e.target).siblings(".edit").eq(0);	
	editElement.show();
	
	// show and add the button_stripe
	var button_stripe = $(".button_stripe").filter(".hidden").clone();
	button_stripe.removeClass("hidden");
	button_stripe.css("display","inline");
	editElement.after(button_stripe);
	
	// add event handlers (for update and cancel and hover) to the button stripe
	button_stripe.find(".update").bind("click",function(e){ update_it(e) });
	button_stripe.find(".clear").bind("click",function(e){ deactivate_edit(e) });
	button_stripe.find("span").hover(
				function(){ $(this).css({"border":"1px solid black", "cursor":"default"})},
				function(){ $(this).css({"border":"0", "cursor":"auto"})}
	);	
}

function init_data()
{
	// the data is urls of the actions where the updates should be posted
	var pathArray = window.location.pathname.split("/");	// To get the title and part from the URL path (/edit2/:title/education)
	var title = pathArray[2];								// third index [2] in the array
	$("#username").data("url","/update/"+title);
	$("#contact").data("url","/update/"+title+"/contacts");
	$("#profile").data("url","/update/"+title+"/profiles");
	$("#skills").data("url","/update/"+title+"/skills");
	$("#educations").data("url","/update/"+title+"/educations");
	$("#experiences").data("url","/update/"+title+"/experiences");
	$("#achievements").data("url","/update/"+title+"/achievements");
	$("#hobbies").data("url","/update/"+title+"/hobbies");
	
	// the data is the urls of the actions where the add requests should be sent
	$("#skills > .addMore").data("url", "/create/"+title+"/skills");
	$("#educations > .addMore").data("url","/create/"+title+"/educations");
	$("#experiences > .addMore").data("url","/create/"+title+"/experiences");

	// the data is the parturls of the actions where the delete requests should be sent
	// /destroy/<part>/<id>
	$("#skills > .delete_button").data("partUrl", "/destroy/skills/");
	$("#education > .delete_button").data("partUrl","/destroy/educations/");
	$("#experiences > .delete_button").data("partUrl","/destroy/experiences/");
}

function deactivate_edit(e)
{
	var button_stripe = $(e.target).parents(".button_stripe").eq(0);	// the target element is the button span
	button_stripe.hide();
	button_stripe.siblings(".edit").hide();
	button_stripe.siblings(".display").show();
	button_stripe.remove();					// remove the button from the dom
}	

function update_it(e)
{
	var button_stripe = $(e.target).parents(".button_stripe").eq(0);	// the target element is the button span
	var editElement = button_stripe.siblings(".edit").eq(0);
	var displayElement = button_stripe.siblings(".display").eq(0);
	var editElementName = editElement.attr("name");
	var editElementValue = editElement.val();
	var postUrl = editElement.parents(".part").eq(0).data("url");
	var authToken = $("*[name='authenticity_token']").eq(0).val();
	
	var postData = new Object();		// creating the hash for the post-data
	postData[editElementName] = editElementValue;
	postData["authenticity_token"] = authToken;
	postData["ajax"] = "true";
	
	$.post(
			postUrl,
			postData,
			function (response){ 
						displayElement.html(editElementValue);
						display_with_linebreaks(displayElement);
						deactivate_edit(e); 
			}
	)	
}

function add_more(e)
{
	var plusButton = $(e.target);
	var inputBoxesDiv = plusButton.siblings(".addInputBoxes");
	inputBoxesDiv.show();
	
	// show and add the button_stripe
	var button_stripe = $(".button_stripe").filter(".hidden").clone();
	button_stripe.removeClass("hidden");
	button_stripe.css("display","inline");
	inputBoxesDiv.after(button_stripe);

	// add event handlers (for update and cancel and hover) to the button stripe
	button_stripe.find(".update").bind("click",function(e){ add_it(e) });
	button_stripe.find(".clear").bind("click",function(e){ deactivate_add(e) });
	button_stripe.find("span").hover(
				function(){ $(this).css({"border":"1px solid black", "cursor":"default"})},
				function(){ $(this).css({"border":"0", "cursor":"auto"})}
	);	
	
	// Hide the plus button for now
	plusButton.hide();
}	

function deactivate_add(e)
{
	var clearButton = $(e.target);
	var button_stripe = clearButton.parents(".button_stripe").eq(0);
	var inputBoxesDiv = button_stripe.siblings(".addInputBoxes").eq(0);
	var plusButton = button_stripe.siblings(".plusButton").eq(0);
	
	inputBoxesDiv.hide();
	button_stripe.remove();	
	plusButton.show();
}

function add_it(e)
{
	var updateButton = $(e.target);
	var addBlock = updateButton.parents(".addMore").eq(0);
	var postUrl = addBlock.data("url");
	var authToken = $("*[name='authenticity_token']").eq(0).val();
	var postData = new Object();		// creating the hash for the post-data
	
	postData["ajax"] = "true";
	postData["authenticity_token"] = authToken;
	addBlock.find(".add").each(function(){
		postData[$(this).attr('name')] = $(this).val();
	});
	
	$.post(
		postUrl,
		postData,
		function(response){
			add_it_callback(e,response);
			deactivate_add(e);	
		}
	);
}

function add_it_callback(e, response)
{
	var responseObj = JSON.parse(response);
	if (responseObj["retVal"] != "created"){
		alert(responseObj["retVal"]);				// XXX: Change this action to something better
		return;	
	}	

	var id = responseObj["id"];
	var addBlock = $(e.target).parents(".addMore").eq(0);
	var partBlock_table = $(e.target).parents(".part").find("table").eq(0);
	var newTd;
	var newTrArr = new Array();
	var newTr = $('<TR></TR>');
	var deleteElement;
	
	addBlock.find(".add").each(function(){
		// For each add element (add input/textarea boxes), 
		// - create and insert a display and and edit element
		// - DOMinsert both to a TD,
		// - push the TD to a TR array (DOM insert)
		// - DOMinsert the TR array to the table that alrady exists
		
		var displayElement, editElement;
		var nameParts, partName, fieldname, nameStr;
		
		displayElement = $('<span></span>');	
		displayElement.addClass('display');
		displayElement.html($(this).val());		// XXX: user provided input - secure it
		
		if ($(this).get(0).tagName=='INPUT'){
			editElement = $('<input type="text">');	
		}
		else if ($(this).get(0).tagName=='TEXTAREA'){		
			editElement = $('<textarea></textarea>');	
		}		
		
		nameParts = splitName($(this).attr("name"));	// eg- split skills[skill_name] into
		partName  = nameParts[0];						//			skills
		fieldName = nameParts[1];						//			skill_name
		nameStr = partName+'['+id+']['+fieldName+']';	// name of the edit element should contain the id

		editElement.attr('name',nameStr);
		editElement.addClass('edit');
		editElement.val($(this).val());			// XXX: user provided input - secure it

		newTd = $('<td></td>');
		newTd.addClass(fieldName);
		newTd.append(displayElement);
		newTd.append(editElement);
		
		newTr.append(newTd);
	});
	
	deleteElement = $('<span class="delete_button">Delete</span>');
	deleteElement.attr('id',id);
	newTd = $('<TD></TD>');
	newTd.append(deleteElement);
	
	newTr.append(newTd);
	partBlock_table.find("TBODY").append(newTr);	
	
	// Add the event handlers
	newTr.find(".edit").hide();
	newTr.find(".display").each(	function() { display_with_linebreaks($(this)); });
	newTr.find(".display").bind("click", function(e){ activate_edit(e);});				
	newTr.find(".display").hover(
					function(){ $(this).css({"background-color":"#ADFF2F", "cursor":"default"})},
					function(){ $(this).css({"background-color":"#dedeff", "cursor":"auto"})}		);
	deleteElement.hover(
					function(){ $(this).css({"background-color":"#FF0000", "cursor":"default"})},
					function(){ $(this).css({"background-color":"#dedeff", "cursor":"auto"})}
	);
	deleteElement.bind("click", function(e){ delete_it2(e); });			
}			

function splitName(nameObj)
{
	// splits string on square brackets. eg -
	// splits 'education[23][level]' into an array {'education', '23', 'level'}
	// or skills[skillset_type]' to array {'skills','skillset_type'}
	var str = nameObj;
	var finalarr = new Array();
	var arr1 = 	str.split('[');
	finalarr.push(arr1[0]);
	for (i=1; i<arr1.length; i++){
		arr2 = arr1[i].split(']');
		finalarr.push(arr2[0]);
	}
	return finalarr;	
}

